import React, { createContext, useContext, useState, useMemo, ReactNode } from 'react';
type ExcelParams = {
  page: number,
  page_size: number,
  sheet_name: string | null,
};
export const excelParamsInit: ExcelParams = {
  page: 1,
  page_size: 30,
  sheet_name: '',
}
type ExcelData = {
  headers?: string[];
  data?: Record<string, any>[];
  sheet_names?: string[];
};

interface ITableContext {
  excelParams: ExcelParams;
  setExcelParams: React.Dispatch<React.SetStateAction<ExcelParams>>;
  excelData: ExcelData;
  setExcelData: React.Dispatch<React.SetStateAction<ExcelData>>;
  tableType: string;
  setTableType: React.Dispatch<React.SetStateAction<string>>;
}

const TableContext = createContext<ITableContext | undefined>(undefined);

export const TableProvider = ({ children }: { children: ReactNode }) => {
  const [excelParams, setExcelParams] = useState<ExcelParams>({
    ...excelParamsInit
  });
  // 表格表头和表数据
  const [excelData, setExcelData] = useState<ExcelData>({
    headers: [],
    data: [],
    sheet_names: [],
  });

  // 是否打开表格详情页
  // tableType: 'list' 表示列表视图，'detail' 表示详情视图
  const [tableType, setTableType] = useState<string>('list');


  // 初始化表格数据
  const initTableData = () => {
    setExcelData({
      headers: [],
      data: [],
      sheet_names: [],
    })
  }

  const contextValue = {
    excelParams,
    setExcelParams,
    excelData,
    setExcelData,
    tableType,
    setTableType,
    initTableData,
  };

  return (
    <TableContext.Provider value={contextValue}>
      {children}
    </TableContext.Provider>



  );
};

export const useTableData = () => {
  const context = useContext(TableContext);
  if (!context) {
    return {
      excelParams: {
        ...excelParamsInit
      },
      setExcelParams: () => { },
      excelData: { headers: [], data: [], sheet_names: [], },
      setExcelData: () => { },
      tableType: 'list',
      setTableType: () => { },
      initTableData: () => { },
    };
  }
  return context;
};
